//
//  CHHTTPSessionManager+Extensions.swift
//  status
//
//  Created by 彳亍 on 2017/3/23.
//  Copyright © 2017年 彳亍. All rights reserved.
//

import UIKit


// MARK: - 微博相关
extension CHHTTPSessionManager {
    
    /// 未读消息
    ///
    /// - Parameter completion: 完成回调
    func unreadStatusCount(completion:@escaping ((_ unread:Int)->())) {
        
        guard let uid = account.uid else { return  }
        
        var parameters = [String:AnyObject]()
        parameters["uid"] = uid as AnyObject?
        
        accessTokenRequest(URLString: CHRemindUnreadCountUrl, parameters: parameters) { (responseObject, isSuccess) in
            
            if !isSuccess {
                completion(0)
                return
            }
            
            guard let responseObject  = responseObject as? [String:AnyObject],
                let unreadCount = responseObject["status"] as? Int
                else {
                    completion(0)
                    return
            }
            completion(unreadCount)
        }
        
    }
    
}

// MARK: - 用户信息
extension CHHTTPSessionManager {
    
    /// 加载用户信息
    ///
    /// - Parameter completion: 完成回调
    func loadUserInfo(completion:@escaping ((_ responseObject:Any?,_ isSuccess:Bool)->())) {
        var parameters = [String :AnyObject]()
        parameters["uid"] = account.uid as AnyObject?
        accessTokenRequest(URLString: CHUsersShowUrl, parameters: parameters, completion: completion)
    }
    
}

// MARK: - 授权相关
extension CHHTTPSessionManager {
    
    func loadAccessToken(code:String,completion:@escaping ((_ isSuccess:Bool)->())){
        
        var parameters = [String:Any]()
        parameters["client_id"] = CHClientId
        parameters["client_secret"] = CHClientScrect
        parameters["grant_type"] = CHGrantType
        parameters["code"] = code
        parameters["redirect_uri"] = CHRedirectUri
        
        request(type: CHHttpType.POST, URLString: CHOAuth2AccessTokenUrl, parameters: parameters) { (responseObject, isSuccess) in
            
            if isSuccess {
                // 请求成功
                self.account.yy_modelSet(withJSON: responseObject ?? [:])
                // 获取用户信息
                self.loadUserInfo(completion: { (responseObject, isSuccess) in
                    self.account.yy_modelSet(withJSON: responseObject ?? [:])
                    // 保存账户信息
                    self.account.saveAccount()
                })
            }
            // 完成回调
            completion(isSuccess)
            
        }
    }
    
}
